﻿namespace Taobao.Tools
{
    using Castle.ActiveRecord;
    using Castle.ActiveRecord.Queries;
    using NHibernate.Criterion;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Threading;
    using System.Windows.Forms;
    using Taobao.Model;
    using Taobao.Top.Api;
    using Taobao.Top.Api.Domain;
    using Taobao.Top.Api.Request;

    public partial class Form1 : Form
    {
       

        public Form1()
        {
            this.InitializeComponent();
        }

        private void autorun()
        {
            try
            {
                this.toolStripStatusLabel2.Text = "自动处理中";
                this.KeepGetTrades();
                this.toolStripStatusLabel2.Text = "自动处理中,得到当前订单";
                this.KeepGetTradeInfo();
                this.toolStripStatusLabel2.Text = "自动处理中,得到订单详细信息";
                this.KeepUpdataTradesInfo();
                this.toolStripStatusLabel2.Text = "自动处理中,得到同步订单发送信息";
                UpdataTradesInfo();
                this.toolStripStatusLabel2.Text = "上次处理结束于" + DateTime.Now + ",下一次将在5分钟后启动";
                this.KeepSent();
                Thread.Sleep(0x927c0);
                this.autorun();
            }
            catch (Exception exp)
            {
                this.toolStripStatusLabel2.Text = "处理出错，程序会在3秒后重新开始 错误：" + exp.Message;
                Thread.Sleep(0xbb8);
                this.autorun();
            }
        }

        private void button1_Click_3(object sender, EventArgs e)
        {
            if (this.button1.Text == "任务暂停")
            {
                this.job.Suspend();
                this.button1.Text = "任务继续";
            }
            else
            {
                this.job.Resume();
                this.button1.Text = "任务暂停";
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            this.TestFindAllByProperty();
            this.TestFindOne();
            this.TestNativeSql();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                ActiveRecordStarter.CreateSchema(typeof(Taobao.Model.Refund));
                MessageBox.Show("初始化退款表成功，请在trade 表中添加EndTime字段,类型为datetime");
            }
            catch (Exception)
            {
                MessageBox.Show("初始化退款表失败");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = string.Empty;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            SendOutSid();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (this.button6.Text == "关闭日志")
            {
                Console.SetOut(this.systemtw);
                this.button6.Text = "打开日志";
            }
            else
            {
                Console.SetOut(this.customtw);
                this.button6.Text = "关闭日志";
            }
        }

        private static TopXmlRestClient CreateClient(Taobao.Model.Shop s)
        {
            return new TopXmlRestClient("http://gw.api.taobao.com/router/rest", s.AppKey, s.AppSecret);
        }
 

        private void DoFindAllByProperty()
        {
            Console.WriteLine(ActiveRecordBase<Taobao.Model.Trade>.FindAllByProperty("TaobaoTid", 0x21908b08d45cL).Length + Environment.NewLine);
        }

        private void DoFindOne()
        {
            Console.WriteLine(ActiveRecordBase<Taobao.Model.Trade>.FindOne(new ICriterion[] { Restrictions.Eq("TaobaoTid", 0x21908b08d45cL) }).ToString() + Environment.NewLine);
        }

        private void DoNativeSql()
        {
            CountQuery cq = new CountQuery(typeof(Taobao.Model.Trade), "TaobaoTid=?", new object[] { 0x21908b08d45cL });
            Console.WriteLine(ActiveRecordBase.ExecuteQuery(cq));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.customtw = new TextBoxWriter(this.textBox1);
            Console.SetOut(this.customtw);
            this.job = new Thread(new ThreadStart(this.autorun));
            this.job.IsBackground = true;
            this.job.Start();
        }

        private static Item GetItemInfo(OrderInfo orderinfo)
        { 
            TopXmlRestClient topClient = new TopXmlRestClient("http://gw.api.taobao.com/router/rest", orderinfo.Trade.Shop.AppKey, orderinfo.Trade.Shop.AppSecret);
            ItemGetRequest req = new ItemGetRequest();
            req.Fields = "iid,detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,auto_repost,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtural";
            //req.Iid = orderinfo.Iid;
            req.NumIid = orderinfo.NumIid;
            return topClient.ItemGet(req); 
        }

        private string getSessionKey(string auth_code)
        {
            try
            {
                HttpWebResponse response = (HttpWebResponse)WebRequest.Create("http://container.api.tbsandbox.com/container?authcode=" + auth_code).GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return "Error";
                }
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                string[] sArray = responseFromServer.Split(new char[] { '&' });
                foreach (string i in sArray)
                {
                    if (i.ToString().StartsWith("top_session"))
                    {
                        return i.ToString().Substring(i.ToString().IndexOf("=") + 1);
                    }
                }
                reader.Close();
                dataStream.Close();
                response.Close();
                return responseFromServer;
            }
            catch (WebException e)
            {
                return ("Error:" + e.Status);
            }
            catch (Exception e)
            {
                return ("Error:" + e.Message);
            }
        }

        public static void GetTrades()
        {
            Console.WriteLine("开始获得所有交易数据 at" + DateTime.Now);
            Taobao.Model.Shop[] ss = ActiveRecordBase<Taobao.Model.Shop>.FindAll();
            foreach (Taobao.Model.Shop s in ss)
            {
                decimal tp;
                int i;
                int pagesize = 100;
                Console.WriteLine(string.Concat(new object[] { "网店名称：", s.Name, "at", DateTime.Now }));
                TopXmlRestClient topClient = CreateClient(s);
                RefundsReceiveGetRequest rgr = new RefundsReceiveGetRequest();
                rgr.Fields = "refund_id, tid,title,total_fee,refund_fee, status, created, modified";
                rgr.PageSize = new int?(pagesize);
                PageList<Taobao.Top.Api.Domain.Refund> rs = topClient.RefundsReceiveGet(rgr);
                Console.WriteLine("退款单数量：{0}", rs.TotalResults);
                foreach (Taobao.Top.Api.Domain.Refund r in rs.Content)
                {
                    SaveRefund(s, r);
                }
                if (rs.TotalResults > pagesize)
                {
                    tp = Convert.ToDecimal(rs.TotalResults) / Convert.ToDecimal(pagesize);
                   
                    i = 2;
                    while (i < decimal.ToInt32(decimal.Ceiling(tp)))
                    {
                        Console.WriteLine("得到第" + i + "页订单");
                        rgr.PageNo = new int?(i);
                        PageList<Taobao.Top.Api.Domain.Refund> rssn = topClient.RefundsReceiveGet(rgr);
                        foreach (Taobao.Top.Api.Domain.Refund rfn in rssn.Content)
                        {
                            SaveRefund(s, rfn);
                        }
                        i++;
                    }
                }
                TradesSoldGetRequest req = new TradesSoldGetRequest();
                req.PageSize = new int?(pagesize);
                req.StartCreated = new DateTime?(DateTime.Parse("1990.01.01"));
                req.EndCreated = new DateTime?(DateTime.Now);
                req.Fields = " title, type, created, sid, tid,end_time, received_payment, alipay_no, iid, num, price, shipping_type";
                req.Status = "WAIT_SELLER_SEND_GOODS";
                PageList<Taobao.Top.Api.Domain.Trade> rsp = topClient.TradesSoldGet(req);
                Console.WriteLine(string.Concat(new object[] { "订单数:", rsp.TotalResults, "从", req.StartCreated, "到", req.EndCreated }));
                if ((rsp.Content == null) || (rsp.Content.Count < 1))
                {
                    Console.WriteLine("没有新增订单");
                }
                else
                {
                    List<Taobao.Top.Api.Domain.Trade> trades = rsp.Content;
                    foreach (Taobao.Top.Api.Domain.Trade t in trades)
                    {
                        SaveTrade(s, t);
                    }
                    if (rsp.TotalResults > pagesize)
                    {
                        tp = Convert.ToDecimal(rsp.TotalResults) / Convert.ToDecimal(pagesize);
                        for (i = 2; i < decimal.ToInt32(decimal.Ceiling(tp)); i++)
                        {
                            Console.WriteLine("得到第" + i + "页订单");
                            req.PageNo = new int?(i);
                            List<Taobao.Top.Api.Domain.Trade> tradesn = topClient.TradesSoldGet(req).Content;
                            foreach (Taobao.Top.Api.Domain.Trade t in tradesn)
                            {
                                SaveTrade(s, t);
                            }
                        }
                    }
                    s.Save();
                }
            }
        }

        private Taobao.Model.Trade[] GetTrades(Taobao.Model.Shop s)
        {
            string sessionKey = this.getSessionKey(s.Name);
            TopXmlRestClient topClient = new TopXmlRestClient("http://gw.api.tbsandbox.com/router/rest", s.AppKey, s.AppSecret);
            TradesSoldGetRequest req = new TradesSoldGetRequest();
            req.Fields = "tid,seller_nick,buyer_nick,status,orders.title,orders.price,orders.num";
            req.PageSize = 40;
            req.Status = "WAIT_SELLER_SEND_GOODS";
            PageList<Taobao.Top.Api.Domain.Trade> rsp = topClient.TradesSoldGet(req, sessionKey);
            if ((rsp.Content == null) || (rsp.Content.Count < 1))
            {
                MessageBox.Show("此会员没有订单，请更换其他会员帐号获取授权码重试");
                return null;
            }
            List<Taobao.Top.Api.Domain.Trade> trades = rsp.Content;
            foreach (Taobao.Top.Api.Domain.Trade t in trades)
            {
            }
            return null;
        }

        public static void GetTradesInfo()
        {
            TopXmlRestClient topClient;
            TradeFullinfoGetRequest req;
            Taobao.Top.Api.Domain.Trade rsp;
            Exception exp;
            Taobao.Model.Trade[] ts = ActiveRecordBase<Taobao.Model.Trade>.FindAllByProperty("ReceiverName", null);
            Console.WriteLine("需要获得详细信息订单数：{0} at{1}", ts.Length, DateTime.Now);
            foreach (Taobao.Model.Trade t in ts)
            {
                topClient = CreateClient(t.Shop);
                req = new TradeFullinfoGetRequest();
                //req.Fields = "num_iid,seller_nick, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo ";
                req.Fields = "num_iid,seller_nick, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders";//.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo ";                
                req.Tid = new long?(t.TaobaoTid);
                try
                {
                    rsp = topClient.TradeFullinfoGet(req);
                    SaveTradeInfo(t, rsp);
                }
                catch (Exception exception1)
                {
                    exp = exception1;
                    Console.WriteLine("获得详细信息订单ID：{0} 出错{1} at{2}", t.TaobaoTid, exp.Message, DateTime.Now);
                }
            }
            ts = ActiveRecordBase<Taobao.Model.Trade>.FindAll(new ICriterion[] { Restrictions.Or(Restrictions.Eq("EndTime", DateTime.Parse("1990.01.01")), Restrictions.IsNull("EndTime")) });
            Console.WriteLine("需要获得EndTime订单数：{0} at{1}", ts.Length, DateTime.Now);
            foreach (Taobao.Model.Trade trade in ts)
            {
                topClient = CreateClient(trade.Shop);
                req = new TradeFullinfoGetRequest();
                //req.Fields = "num_iid,seller_nick,end_time, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo,orders.num_iid ";
                req.Fields = "num_iid,seller_nick,end_time, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders";//,orders.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo,orders.num_iid ";
                req.Tid = new long?(trade.TaobaoTid);
                try
                {
                    rsp = topClient.TradeFullinfoGet(req);
                    SaveTradeInfo(trade, rsp);
                }
                catch (Exception exception2)
                {
                    exp = exception2;
                    Console.WriteLine("获得EndTime 订单ID：{0} 出错{1} at{2}", trade.TaobaoTid, exp.Message, DateTime.Now);
                }
            }
        }

    

        private void KeepGetTradeInfo()
        {
            try
            {
                GetTradesInfo();
            }
            catch (Exception exp)
            {
                Console.WriteLine("得到交易详细信息出错：{0},程序将重新启动", exp.Message);
                this.KeepGetTradeInfo();
            }
        }

        private void KeepGetTrades()
        {
            try
            {
                GetTrades();
            }
            catch (Exception exp)
            {
                Console.WriteLine("获得所有交易数据出错：{0},程序将重新启动", exp.Message);
                this.KeepGetTrades();
            }
        }

        private void KeepSent()
        {
            try
            {
                SendOutSid();
            }
            catch (Exception exp)
            {
                Console.WriteLine("提交物流信息出错：{0},程序将重新启动", exp.Message);
                this.KeepSent();
            }
        }

        private void KeepUpdataTradesInfo()
        {
            try
            {
                UpdataTradesInfo();
            }
            catch (Exception exp)
            {
                Console.WriteLine("跟新交易详细信息出错：{0},程序将重新启动", exp.Message);
                this.KeepUpdataTradesInfo();
            }
        }

        private static void SaveRefund(Taobao.Model.Shop s, Taobao.Top.Api.Domain.Refund r)
        {
            Taobao.Model.Refund rf;
            CountQuery cq = new CountQuery(typeof(Taobao.Model.Refund), "RefundID=?", new object[] { r.RefundId });
            if (((int)ActiveRecordBase.ExecuteQuery(cq)) == 0)
            {
                rf = new Taobao.Model.Refund();
                rf.Created = DateTime.Parse(r.Created);
                rf.Modified = DateTime.Parse(r.Modified);
                rf.Status = r.Status;
                rf.TaobaoID = r.Tid;
                rf.RefundID = r.RefundId;
                rf.Title = r.Title;
                if (r.RefundFee != null)
                {
                    rf.Refundfee = decimal.Parse(r.RefundFee);
                }
                if (r.TotalFee != null)
                {
                    rf.Totalfee = decimal.Parse(r.TotalFee);
                }
                rf.Shop = s;
                rf.Create();
                Console.WriteLine(string.Concat(new object[] { "获得退款单号：", r.RefundId, "at", DateTime.Now }));
            }
            else
            {
                rf = ActiveRecordBase<Taobao.Model.Refund>.FindOne(new ICriterion[] { Restrictions.Eq("RefundID", r.RefundId) });
                if (r.Modified != null)
                {
                    rf.Modified = DateTime.Parse(r.Modified);
                }
                rf.Status = r.Status;
                if (r.RefundFee != null)
                {
                    rf.Refundfee = decimal.Parse(r.RefundFee);
                }
                if (r.TotalFee != null)
                {
                    rf.Totalfee = decimal.Parse(r.TotalFee);
                }
                rf.Save();
                Console.WriteLine(string.Concat(new object[] { "更新退款单号：", r.RefundId, "at", DateTime.Now }));
            }
        }

        private static void SaveTrade(Taobao.Model.Shop s, Taobao.Top.Api.Domain.Trade t)
        {
            CountQuery cq = new CountQuery(typeof(Taobao.Model.Trade), "TaobaoTid=?", new object[] { t.Tid });
            if (((int)ActiveRecordBase.ExecuteQuery(cq)) == 0)
            {
                Taobao.Model.Trade art = new Taobao.Model.Trade();
                art.AlipayNo = t.AlipayNo;
                art.Buyer_nick = t.BuyerNick;
                art.BuyerMemo = t.BuyerMemo;
                art.OrderNum = (short)t.Num;
                art.OrderPrice = t.Payment;
                art.Shop = s;
                art.Status = t.Status;
                art.BuyerMemo = t.BuyerMemo;
                art.Seller_nick = t.SellerNick;
                art.TaobaoTid = t.Tid;
                art.Created = new DateTime?(DateTime.Parse(t.Created));
                Console.WriteLine("订单创建日期" + art.Created);
                if (t.PayTime != null)
                {
                    art.PayTime = new DateTime?(DateTime.Parse(t.PayTime));
                }
                else
                {
                    art.PayTime = new DateTime?(DateTime.Parse("1990.01.01"));
                }
                if (t.EndTime != null)
                {
                    art.EndTime = new DateTime?(DateTime.Parse(t.EndTime));
                }
                else
                {
                    art.EndTime = new DateTime?(DateTime.Parse("1990.01.01"));
                }
                art.Create();
                Console.WriteLine("保存订单成功，订单ID：{0} at{1}", t.Tid, DateTime.Now);
            }
            else
            {
                Console.WriteLine("订单已经存在 订单:" + t.Tid);
            }
        }

        private static void SaveTradeInfo(Taobao.Model.Trade art, Taobao.Top.Api.Domain.Trade trade)
        {
            TransactionScope t2 = new TransactionScope(TransactionMode.New);
            try
            {
                art.ReceiverAddress = trade.ReceiverAddress;
                art.ReceiverCity = trade.ReceiverCity;
                art.ReceiverDistrict = trade.ReceiverDistrict;
                art.ReceiverMobile = trade.ReceiverMobile;
                art.ReceiverName = trade.ReceiverName;
                art.ReceiverPhone = trade.ReceiverPhone;
                art.ReceiverState = trade.ReceiverState;
                art.ReceiverZip = trade.ReceiverZip;
                art.SellerName = trade.SellerName;
                art.SellerMobile = trade.SellerMobile;
                art.BuyerAlipayNo = trade.BuyerAlipayNo;
                art.PostFee = trade.PostFee;
                art.ShippingType = trade.ShippingType;
                art.Type = trade.Type;
                art.Discount_Fee = new decimal?(trade.Orders.Sum<Taobao.Top.Api.Domain.Order>(delegate(Taobao.Top.Api.Domain.Order o)
                {
                    if (o.DiscountFee != null)
                    {
                        return decimal.Parse(o.DiscountFee);
                    }
                    return 0M;
                }));
                art.Adjust_Fee = new decimal?(trade.Orders.Sum<Taobao.Top.Api.Domain.Order>(delegate(Taobao.Top.Api.Domain.Order o)
                {
                    if (o.AdjustFee != null)
                    {
                        return decimal.Parse(o.AdjustFee);
                    }
                    return 0M;
                }));
                art.Payment = trade.Payment;
                if (trade.PayTime != null)
                {
                    art.PayTime = new DateTime?(DateTime.Parse(trade.PayTime));
                }
                if (trade.EndTime != null)
                {
                    art.EndTime = new DateTime?(DateTime.Parse(trade.EndTime));
                }
                art.Status = trade.Status;
                art.Seller_nick = trade.SellerNick;
                art.Buyer_nick = trade.BuyerNick;
                art.BuyerMemo = "买家备注：" + trade.BuyerMemo + "||买家留言：" + trade.BuyerMessage;
                art.SellerMemo = trade.SellerMemo;
                int sellerFlag = trade.SellerFlag;
                art.SellerFlag = trade.SellerFlag.ToString();
                art.AlipayNo = trade.AlipayNo;
                art.OrdersTitle = trade.Orders[0].Title;
                art.OrderNum = (short)trade.Orders.Count;
                if (art.OrderInfoes.Count == 0)
                {
                    foreach (Taobao.Top.Api.Domain.Order o in trade.Orders)
                    {
                        OrderInfo oi = new OrderInfo();
                        oi.NumIid = o.NumIid;
                        oi.Title = o.Title;
                        oi.Trade = art;
                        oi.Number = o.Num;
                        oi.Price = o.Price;
                        oi.Iid = o.Iid;
                        oi.ItemMealName = o.ItemMealName;
                        if (o.AdjustFee != null)
                        {
                            oi.Adjust_Fee = new decimal?(decimal.Parse(o.AdjustFee));
                        }
                        if (o.DiscountFee != null)
                        {
                            oi.Discount_Fee = new decimal?(decimal.Parse(o.DiscountFee));
                        }
                        if (o.Payment != null)
                        {
                            oi.Payment = new decimal?(decimal.Parse(o.Payment));
                        }
                        long refundId = o.RefundId;
                        oi.RefundId = new long?(o.RefundId);
                        if (o.Status != null)
                        {
                            oi.Status = o.Status;
                        }
                        if (o.Modified != null)
                        {
                            oi.Modified = new DateTime?(DateTime.Parse(o.Modified));
                        }
                        oi.Save();
                        Item item = GetItemInfo(oi);
                        oi.SkuPropertiesName = o.SkuPropertiesName;
                        oi.OuterIId = item.OuterId;
                        oi.NumIid = item.NumIid;
                        oi.SkuID = o.SkuId;
                        oi.Save();
                    }
                }
                art.Save();
                OutSent os = art.OutSent ?? new OutSent();
                if (art.Status == "WAIT_SELLER_SEND_GOODS")
                {
                    os.Message = "待发货";
                }
                else
                {
                    os.Message = "发货成功";
                    Console.WriteLine("更新一个已发货信息,订单ID：{0}", art.TaobaoTid);
                }
                os.Trade = art;
                os.Save();
                Console.WriteLine("获得详细信息订单ID：{0}  at{1}", art.TaobaoTid, DateTime.Now);
                t2.VoteCommit();
            }
            catch (Exception)
            {
                t2.VoteRollBack();
            }
            finally
            {
                if (t2 != null)
                {
                    t2.Dispose();
                }
            }
        }

        public static void sellerSentTrade(Taobao.Model.Trade trade)
        {
            TopXmlRestClient client = new TopXmlRestClient("http://gw.api.taobao.com/router/rest", trade.Shop.AppKey, trade.Shop.AppSecret);
            DeliverySendRequest req = new DeliverySendRequest();
            req.Tid = new long?(trade.TaobaoTid);
            if (trade.OutSent.OrderType != "virtual_goods")
            {
                if (trade.OutSent.CompanyCode == null)
                {
                    req.CompanyCode = trade.Shop.Sender.CompanyCode;
                }
                else
                {
                    req.CompanyCode = trade.OutSent.CompanyCode;
                }
                req.Memo = trade.OutSent.Memo;
                req.OutSid = trade.OutSent.OutSid;
                req.SellerAddress = trade.Shop.Sender.Address;
                req.SellerAreaId = trade.Shop.Sender.AreaID;
                req.SellerMobile = trade.Shop.Sender.Mobile;
                req.SellerName = trade.Shop.Sender.Name;
                req.SellerZip = trade.Shop.Sender.Zip;
                req.SellerPhone = trade.Shop.Sender.Phone;
            }
            else
            {
                req.OrderType = trade.OutSent.OrderType;
            }
            try
            {
                if (client.DeliverySend(req).IsSuccess)
                {
                    trade.OutSent.Message = "发货成功";
                    trade.Status = "WAIT_BUYER_CONFIRM_GOODS";
                    Console.WriteLine("发货成功");
                }
                else
                {
                    trade.OutSent.Message = "发货失败";
                    trade.OutSent.Failure = "1";
                }
            }
            catch (Exception exp)
            {
                trade.OutSent.Failure = exp.ToString();
            }
            trade.OutSent.Update();
            trade.Save();
        }

        public static void SendOutSid()
        {
            Exception e;
            Console.WriteLine("待发货订单数：" + ActiveRecordBase<OutSent>.FindAllByProperty("Message", "待发货").Length);
            Console.WriteLine("待同步订单数：" + ActiveRecordBase<OutSent>.FindAll(new ICriterion[] { Restrictions.Eq("Message", "待发货"), Restrictions.IsNotNull("OutSid") }).Length);
            foreach (OutSent os in ActiveRecordBase<OutSent>.FindAll(new ICriterion[] { Restrictions.Eq("Message", "待发货"), Restrictions.IsNotNull("OutSid"), Restrictions.IsNotNull("CompanyCode"), Restrictions.IsNull("Failure") }))
            {
                try
                {
                    sellerSentTrade(os.Trade);
                }
                catch (Exception exception1)
                {
                    e = exception1;
                    Console.WriteLine("发送时出错,错误为:" + e.Message);
                    Thread.Sleep(0xbb8);
                    sellerSentTrade(os.Trade);
                }
                Console.WriteLine("发送一次");
            }
            OutSent[] virtual_goods = ActiveRecordBase<OutSent>.FindAll(new ICriterion[] { Restrictions.Eq("Message", "待发货"), Restrictions.Eq("OrderType", "virtual_goods") });
            Console.WriteLine("待发虚拟物品数量为：" + virtual_goods.Length);
            foreach (OutSent os in virtual_goods)
            {
                try
                {
                    sellerSentTrade(os.Trade);
                }
                catch (Exception exception2)
                {
                    e = exception2;
                    Console.WriteLine("发送时出错,错误为:" + e.Message);
                    Thread.Sleep(0xbb8);
                    sellerSentTrade(os.Trade);
                }
                Console.WriteLine("发送一次");
            }
        }

        private void TestFindAllByProperty()
        {
            TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
            this.DoFindAllByProperty();
            TimeSpan end = new TimeSpan(DateTime.Now.Ticks);
            Console.WriteLine("TestFindAllByProperty 用时:" + end.Subtract(start).TotalMilliseconds + Environment.NewLine);
        }

        private void TestFindOne()
        {
            TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
            this.DoFindOne();
            TimeSpan end = new TimeSpan(DateTime.Now.Ticks);
            Console.WriteLine("TestFindOne 用时:" + end.Subtract(start).TotalMilliseconds + Environment.NewLine);
        }

        private void TestNativeSql()
        {
            TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
            this.DoNativeSql();
            TimeSpan end = new TimeSpan(DateTime.Now.Ticks);
            Console.WriteLine("TestNativeSql 用时:" + end.Subtract(start).TotalMilliseconds + Environment.NewLine);
        }

        public static void UpdataTradesInfo()
        {
            Taobao.Model.Trade[] ts = ActiveRecordBase<Taobao.Model.Trade>.FindAllByProperty("Status", "WAIT_SELLER_SEND_GOODS");
            Console.WriteLine("需要跟新的订单数：" + ts.Length.ToString());
            foreach (Taobao.Model.Trade t in ts)
            {
                TopXmlRestClient topClient = CreateClient(t.Shop);
                TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
                //req.Fields = "num_iid,seller_nick, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo ";
                req.Fields = "num_iid,seller_nick, buyer_nick, title, type, created, sid, tid,  status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time, buyer_memo, seller_memo, alipay_no, buyer_message,  iid, num, price, buyer_alipay_no, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address, receiver_zip, receiver_mobile, receiver_phone, buyer_email, shipping_type, trade_memo, is_3D ,orders";//.title, orders.price,orders.oid, orders.num, orders.iid,  orders.status, orders.tid, orders.total_fee, orders.payment, orders.discount_fee, orders.adjust_fee, orders.timeout_action_time,orders.sku_properties_name, orders.item_meal_name, item_memo ";                                
                req.Tid = new long?(t.TaobaoTid);
                Taobao.Top.Api.Domain.Trade rsp = topClient.TradeFullinfoGet(req);
                SaveTradeInfo(t, rsp);
            }
        }

        private void 获得待发货订单数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        private void 删除数据结构ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ActiveRecordStarter.DropSchema();
                MessageBox.Show("删除数据结构成功");
            }
            catch
            {
                MessageBox.Show("删除数据结构失败");
            }
        }
    }
}

